/**
        Author: SpringHack - springhack@live.cn
        Last modified: 2017-02-09 21:32:18
        Filename: src/server/main.js
        Description: Created by SpringHack using vim automatically.
**/
import express from 'express';
import signer from './signer.js';
import xml from './xml.js';
import config from './config.js'

let licenseSigner = new signer(config.PRIVATE_KEY);
let app = express();

app.use((req, res, next) => {
    console.log('');
    console.log('LOG ===========>:');
    console.log('Request URL:', req.url);
    console.log('Request query:', req.query);
    console.log('END ===========>:');
    next();
});

app.get('*/releaseTicket.action', (req, res) => {
    let ret = xml.releaseTicket(config, req, res);
    res.set('Content-Type', 'text/xml');
    res.send(ret);
});

app.get('*/prolongTicket.action', (req, res) => {
    let ret = xml.prolongTicket(config, req, res);
    res.set('Content-Type', 'text/xml');
    res.send(`<!-- ${licenseSigner.sign(ret)} -->` + '\n' + ret);
});

app.get('*/obtainTicket.action', (req, res) => {
    let ret = xml.obtainTicket(config, req, res);
    res.set('Content-Type', 'text/xml');
    res.send(`<!-- ${licenseSigner.sign(ret)} -->` + '\n' + ret);
});

app.get('*/ping.action', (req, res) => {
    let ret = generateXml.ping(config, req, res);
    res.set('Content-Type', 'text/xml');
    res.send(`<!-- ${licenseSigner.sign(ret)} -->` + '\n' + ret);
});

app.get('/*', (req, res) => {
    res.send('Hello World!');
});

app.listen(process.env.PORT || config.PORT, () => {
    console.log('Jetbrains License Server Start on ' + (process.env.PORT || config.PORT));
    console.log('prease CTRL+C to stop it!');
});
